package com.news_back.common;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

@Slf4j
public class Md5Util {
    public static String getMd5(String string) {
        if (StringUtils.isNotBlank(string)) {
            try {
                return md5(string.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("", e);
            }
        }
        return null;
    }

    public static String md5(byte[] bytes) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        StringBuilder sb = new StringBuilder(40);
        try {
            byte[] bs = md5.digest(bytes);
            for (byte x : bs) {
                if ((x & 0xff) >> 4 == 0) {
                    sb.append("0").append(Integer.toHexString(x & 0xff));
                } else {
                    sb.append(Integer.toHexString(x & 0xff));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

}
